package codetop.kuaishou.T113;

import util.TreeNode;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: 18362
 * @Create: 2022-09-14 17:10:00 星期三
 */
class Solution {
    public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
        List<List<Integer>> res = new ArrayList<>();
        dfs(root, 0, targetSum, new ArrayList<>(), res);
        return res;
    }

    private void dfs(TreeNode root, int sum, int targetSum, List<Integer> path, List<List<Integer>> res) {
        if (root == null)
            return;
        path.add(root.val);
        sum += root.val;
        if (root.left == null && root.right == null) {
            if (sum == targetSum)
                res.add(new ArrayList<>(path));
            path.remove(path.size() - 1);
            return;
        }
        dfs(root.left, sum, targetSum, path, res);
        dfs(root.right, sum, targetSum, path, res);
        path.remove(path.size() - 1);
    }
}